import { app, BrowserWindow } from 'electron'
import { ChildProcess, fork } from 'child_process'
import { isDevEnv } from '@/EnvUtil'

let serverProcess: ChildProcess = null

function createServerProcess() {
  // require('./koa-server/server') // 打包为exe文件之后，这样也可以启动koa服务
  // exec，spawn，fork 不同子进程开启方式区别详见：https://blog.csdn.net/chy555chy/article/details/52556318
  serverProcess = fork(require.resolve('./koa-server/server'))
  serverProcess.on('close', (code) => {
    console.log('子进程已经退出', code)
  })
}

const createWindow = () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
  })

  if (isDevEnv()) {
    win.loadFile('../vue-gui/index.html')
  } else {
    win.loadFile('./vue-gui/index.html')
  }
}

app.whenReady().then(() => {
  createServerProcess()
  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})
